package com.structure.link;

/**
 * 单链表
 * @author David
 *
 */
public class LinkList {
	public Node first;//头节点
	private int pos = 0;//节点的位置
	
	public LinkList(){
		first = null;
	}
	
	//插入一个头节点
	public void addFirstNode(Object data){
		Node node = new Node(data);
		node.next = first;
		first = node;
		
	}
	
	//删除一个头节点，并返回头节点
	public Node deleteFirstNode(){
		first = first.next;
		return first;
	}
	
	//在任意位置插入节点。
	public void add(int index,Object data){
		Node node = new Node(data);
		Node find = first;
		while(pos!=index){
			find = find.next;
			pos++;
		}
		node.next = find.next;
		find.next = node;
		pos = 0;
	}
	
	//在任意位置删除节点
	public void delete(int index){
		Node find = first;
		Node lastNode = null;
		while(pos!=index){
			lastNode = find;
			find = find.next;
			pos++;
		}
		if(lastNode!=null){
			lastNode.next = find.next;
		}else{
			first = find.next;
		}
		pos = 0;
		
	}
	
	//遍历所有的node
	public void dispalyAllNode(){
		Node find = first;
		while(find!=null){ 
			find.display();
			find = find.next;
		}
	}
	
	
	public static void main(String[] args){
		LinkList link = new LinkList();
		link.addFirstNode("a");
		link.addFirstNode("b");
		link.addFirstNode("c");
		link.addFirstNode("d");
//		link.add(1, "e");
//		link.deleteFirstNode();
		link.delete(2);
		link.dispalyAllNode();
		
	}
	
	
}
